//
//  CLUserAccountViewModel.swift
//  CLWeibo
//
//  Created by 陈亮 on 16/7/12.
//  Copyright © 2016年 陈亮. All rights reserved.
//

import UIKit
//封装OAuthd登录的相关接口
class CLUserAccountViewModel: NSObject {
    
    //単例访问点
    static let sharedUserAccount:CLUserAccountViewModel = CLUserAccountViewModel()
    //获取从沙盒中解档出来的对象
    var userAccount :CLUserAccount?{
        //解档用户对象
        return CLUserAccount.loadUserAccount()
    }
    
    //构造函数私有化
    private override init() {
        super.init()
    }
    //封装判断accessToken是否为nil来判断登录与否
    var isLogin:Bool {
        
        return accesstoken != nil
    }
    //根据accesstoken判断是否为nil
    var accesstoken:String? {
        //判断accesstoken是否为nil  为nil则表示没有登录
        guard let token = userAccount?.access_token else {
            return nil
        }
        //代码运行到这里 表示一定accesstoken一定有值
        //判断对比当前的时间跟过期时间  如果过期时间大于当前时间  表示没有国企
        let result = userAccount?.expiresDate?.compare(NSDate())
        
        //使用降序表示我们进行从大到小
        if result == NSComparisonResult.OrderedDescending {
            return token
        }else
        {
            return nil
        }
    
    }
    
    // MARK:  通过授权码 获取accessToken
    func requestAccessToken(code :String,callback :(isSuccess:Bool) ->()){
        CLNetWorkingTool.sharedTool.requestAccessToken(code) { (response, error) -> () in
            print(error)
            if error != nil {
                callback(isSuccess: false)
                return
            }
            guard let dic = response as? [String :AnyObject] else {
                callback(isSuccess: false)
                return
            }
            let userAccount = CLUserAccount(dic: dic )
            
            self.requestUserInfo(userAccount,callback:callback)
        }
    }
    // MARK:  获取用户信息
    func requestUserInfo(userAccount :CLUserAccount,callback :(isSuccess:Bool) ->()){
        CLNetWorkingTool.sharedTool.requestUserInfo(userAccount) { (response, error) -> () in
            if error != nil {
                callback(isSuccess: false )
                return
            }
            guard let dic = response as? [String :AnyObject] else {
                callback(isSuccess: false )
                return
            }
            let name = dic["name"]
            let avatar_large = dic["avatar_large"]
            //设置用户名和头像
            userAccount.name = name as? String
            userAccount.avatar_large = avatar_large as? String
            //保存用户对象
            let result = userAccount.saveUserAccount()
            if result{
                callback(isSuccess: true)
            }else {
                callback(isSuccess: false)
            }
            
        }
    }
    
}



